package com.ruiysoft.controller.wx.api.service;

import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruiysoft.controller.wx.dto.DoTransferDto;
import com.ruiysoft.controller.wx.dto.InnerWeChatACodeDto;
import com.ruiysoft.controller.wx.dto.OrderPayDto;
import com.ruiysoft.controller.wx.dto.WeChatACodeDto;
import com.ruiysoft.controller.wx.res.JsSignResponse;
import com.ruiysoft.controller.wx.res.TokenResponse;
import com.ruiysoft.controller.wx.res.TransferredResponse;
import com.ruiysoft.entity.sys.SysShopPayPlatform;
import com.ruiysoft.entity.sys.SysShopPersonnel;
import com.ruiysoft.service.sys.ISysShopPayPlatformService;
import com.ruiysoft.service.sys.ISysShopPersonnelService;
import com.ruiysoft.service.sys.ISysUserShopRelationService;
import com.ruiysoft.service.sys.clent.LoginContextUtil;
import com.ruiysoft.service.wechat.IWeChatService;
import com.ruiysoft.util.WeChatUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by 化增光 on 2018/11/3.
 */
@Service
public class WeChatApiService {

    @Resource
    IWeChatService iWeChatService;

    @Resource
    ISysShopPayPlatformService iSysShopPayPlatformService;

    @Resource
    ISysShopPersonnelService iSysShopPersonnelService;

    @Resource
    ISysUserShopRelationService iSysUserShopRelationService;

//    @Resource
//    ISysUserService iSysUserService;

    public TokenResponse getAccessToken(SysShopPayPlatform payPlatform) {
        String access_token = iWeChatService.getAccessToken(payPlatform.getAppId(),payPlatform.getSecret());
        return new TokenResponse().token(access_token);
    }

    public JsSignResponse jsSign(SysShopPersonnel personnel, @Valid OrderPayDto order) {
        //后续根据shopId 获取
//        String appid = "wx9308044613fae7f8";
//        String paykey = "b979655a134bd955c185676ab43523aa";
//        String macid = "1249480601";
       // SysMicroShop shop = LoginContextUtil.instance().getEntryMicroShop();
        SysShopPayPlatform payPlatform = LoginContextUtil.instance().getShopPayPlatformByAppId(personnel.getAppId());
        String prepayid = iWeChatService.getPrepayid(payPlatform.getAppId(),payPlatform.getPayKey(),payPlatform.getMchId(),personnel.getOpenid(),order);

        Long timeStamp = System.currentTimeMillis() / 1000;
        String nonceStr = UUID.randomUUID().toString().replace("-", "");

        Map<String, String> payparams = new HashMap<>();
        payparams.put("appId", payPlatform.getAppId());
        payparams.put("timeStamp", String.valueOf(timeStamp));
        payparams.put("nonceStr", nonceStr);
        payparams.put("package", "prepay_id=" + prepayid);
        payparams.put("signType", "MD5");
        String paySign = WeChatUtil.sign(payparams, payPlatform.getPayKey());

        JsSignResponse response = new JsSignResponse()
                .timeStamp(timeStamp)
                ._package("prepay_id=" + prepayid)
                .nonceStr(nonceStr)
                .signType("MD5")
                .paySign(paySign);
        return response;
    }

    public byte[] wxacodeunlimit(Long shopId, String appId, String secret, @Valid WeChatACodeDto aCodeDto, SysShopPersonnel personnel) {
        String access_token = iWeChatService.getAccessToken(appId,secret);

        StringBuffer scene = new StringBuffer();
        scene.append(shopId)
                .append("#").append(personnel.getId())
                .append("#").append(aCodeDto.getScene());


        return iWeChatService.wxacodeunlimit(access_token,scene.toString(),aCodeDto.getUrl());

    }

    public TransferredResponse doTransfer(DoTransferDto dto) {
        System.out.println("调用转账接口 入参:"+ JSON.toJSONString(dto));
//        Assert.notNull(dto.getShopId(),"店铺主键异常");
//        SysShopPayPlatform platform = iSysShopPayPlatformService.selectShopPayPlatformByShopId(dto.getShopId());
//        Assert.notNull(platform,"未获取到店铺支付平台信息");
//        if (null == dto.getPersonnelId()){
//            SysUserShopRelation relation = iSysUserShopRelationService.selectOne(new EntityWrapper<SysUserShopRelation>().eq("shop_id",dto.getShopId()));
//            SysUser user = iSysUserService.selectById(relation.getUserId());
//            Assert.notNull(user,"店主信息异常");
//            Assert.notNull(user.getPersonnelId(),"店主未绑定小程序");
//            dto.setPersonnelId(user.getPersonnelId());
//        }
        Assert.notNull(dto.getPersonnelId(),"人员信息主键异常");
        SysShopPersonnel personnel = iSysShopPersonnelService.getById(dto.getPersonnelId());
        Assert.notNull(personnel,"获取到人员信息异常");
        SysShopPayPlatform platform = iSysShopPayPlatformService.getOne(new QueryWrapper<SysShopPayPlatform>().eq("app_id",personnel.getAppId()));
        Assert.notNull(platform,"获取店铺商户平台信息异常");
        return iWeChatService.doTransfer(platform,personnel.getOpenid(),dto.getTransactionNo(),dto.getAmount(),dto.getDesc());
    }

    public SysShopPayPlatform selectShopPayPlatformByAppIdAndMachId(String appid, String mch_id) {
        return iSysShopPayPlatformService.getOne(new QueryWrapper<SysShopPayPlatform>().eq("app_id",appid).eq("mch_id",mch_id));
    }

    public byte[] wxacodeunlimit(String secret, @Valid InnerWeChatACodeDto aCodeDto) {
        String access_token = iWeChatService.getAccessToken(aCodeDto.getAppId(),secret);
        StringBuffer scene = new StringBuffer();
        scene.append(aCodeDto.getShopId());
        return iWeChatService.wxacodeunlimit(access_token,scene.toString(),aCodeDto.getUrl());
    }

//    public void refund(int type, Long shopId, String orderNo, String refundNo, BigDecimal totalAmount, BigDecimal refundAmount){
//        iWeChatService.refund(type,orderNo,refundNo,totalAmount,refundAmount);
//    }


}
